#coding=utf-8
import re, datetime
from dateutil.relativedelta import *
re_fenzhong = r'(\d{1,2})分钟前'
re_jintian = r'今天 (\d{1,2}):(\d{1,2})'
re_yueri = r'(\d{1,2})月(\d{1,2})日 (\d{1,2}):(\d{1,2})'
re_nian = r'(\d{4})-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2})'

test_date_string = ['2009-12-4 15:52', '1月25日 18:51', '5秒前', '3分钟前', '43分钟前', '今天 17:28', '今天 07:28']

def _has_digit(s):
  m = re.search(r'\d', s)
  if m:
    return True
  else:
    return False

def _remove_quotes(s):
  s = s.replace("'", '')
  return s

def _parse_date(datestring, now):
  #print datestring
  n = now
  re_miao = r'(\d{1,2})秒前'
  re_fenzhong = r'(\d{1,2})分钟前'
  re_jintian = r'今天 (\d{1,2}):(\d{1,2})'
  re_yueri = r'(\d{1,2})月(\d{1,2})日 (\d{1,2}):(\d{1,2})'
  re_nian = r'(\d{4})-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2})'
  
  m = re.match(re_miao, datestring)
  if m:
    mins = 1
    r = now + relativedelta(minutes=-mins)
    return datetime.datetime(r.year, r.month, r.day, r.hour, r.minute)
    
  m = re.match(re_fenzhong, datestring)
  if m:
    mins = int(m.group(1))
    r = now + relativedelta(minutes=-mins)
    return datetime.datetime(r.year, r.month, r.day, r.hour, r.minute)
  
  m = re.match(re_jintian, datestring)  
  if m:
    h = int(m.group(1))
    m = int(m.group(2))
    return datetime.datetime(n.year, n.month, n.day, h, m)
  
  m = re.match(re_yueri, datestring)
  if m:
     month = int(m.group(1))
     day = int(m.group(2))
     hour = int(m.group(3))
     mins = int(m.group(4))
     return datetime.datetime(n.year, month, day, hour, mins)
  
  m = re.match(re_nian, datestring)
  if m:
    year = int(m.group(1))
    month = int(m.group(2))
    day = int(m.group(3))
    hour = int(m.group(4))
    mins = int(m.group(5))
    return datetime.datetime(year, month, day, hour, mins)

  return None
    
def _get_created_at(html_content, now=datetime.datetime.now()):
  h = html_content
  data = re.findall(r'<cite><a href=.+?><strong>(.+?)</strong></a></cite>', h)
  #print data
  data = [_parse_date(i, now) for i in data if _parse_date(i, now)]
  return data

def _get_created_at2(html_content):
    h = html_content
    data = re.findall(r'<cite><a href=.+?><strong date="(.+?)">', h)
    return data

